package com.dragons.dragonsvf.controller;

import com.dragons.dragonsvf.config.DynamicMinioConfig;
//import com.dragons.dragonsvf.config.MinioConfig;
import com.dragons.dragonsvf.dao.MemeryInfoMapper;
import com.dragons.dragonsvf.entities.MemeryInfo;
import com.dragons.dragonsvf.entities.MemeryInfoDTO;
import com.dragons.dragonsvf.entities.ResponseDTO;
import com.dragons.dragonsvf.utils.idbuilder.IdUtil;
import com.dragons.dragonsvf.utils.image_compress.ImageCompressionUtil;
import com.dragons.dragonsvf.utils.netUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Dragons.G
 * @date 2025-03-15 14:50:39
 * @description 文件上传控制器
 */
@RestController
public class FileUploadController {

    //@Autowired
    //MinioConfig minioConfig;

    @Autowired
    DynamicMinioConfig minioConfig;

    @Autowired
    MemeryInfoMapper memeryInfoMapper;

    /**
     * 注册上传头像
     * @param file 上传文件
     * @param formData
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/uploadAvatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseDTO uploadAvatar(
        @RequestParam("avatar") MultipartFile file, // 和前端fieldName一致
        @RequestParam(required = false) Map<String, String> formData
    ) throws Exception {
        MultipartFile multipartFile = ImageCompressionUtil.compressMultipartFile(file);
        String s = minioConfig.putAvatarObject(multipartFile);
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setCode(200);
        responseDTO.setMsg("文件上传成功");
        responseDTO.setData(s);
        return responseDTO;
    }

    @DeleteMapping("/deleteAvatar")
    public ResponseDTO deleteAvatar(@RequestParam String url) {
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setCode(200);
        responseDTO.setMsg("文件删除成功");
        responseDTO.setData(null);
        return responseDTO;
//        try {
//            // 解析MinIO对象名称
//            String objectName = url.substring(url.lastIndexOf("/") + 1);
//            minioService.removeObject(objectName);
//            return ResponseDTO.success();
//        } catch (Exception e) {
//            return ResponseDTO.error(500, "文件删除失败: " + e.getMessage());
//        }
    }

    /**
     * 回忆录上传文件
     * @param file 上传文件
     * @param formData
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/uploadMemery", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseDTO uploadMemery(
        @RequestParam("imgFile") MultipartFile file, // 和前端 fieldName 一致
        @RequestParam(required = false) Map<String, Object> formData
    ) throws Exception {
        double size = ImageCompressionUtil.getImageSizeMB(file);
        double scal = 0.0;
        double quality = 0.0;
        // 根据图片大小传递参数
        // 小于1 MB 的不压缩
        // 1-5   scale 1 qulity 0.3
        // 5 - 10  scale 0.6  qulity 0.3
        // 10-20 scale 0.65  qulity 0.2
        // 20 以上的 scale 1  qulity 0.1

        // 小于 1MB的不压缩
        // 如果是png 则 判断大小  如果大于4 小于 5MB 则 scale 0.3 qulity 0.2
        // 如果是 1 - 3 MB   scale 4 qulity 0.2
        if (size < 1) { scal= 1.0; quality = 1.0; }
        if (size > 1 && size <= 5) { scal= 1.0; quality = 0.3; }
        if (size > 5 && size <= 10) { scal= 0.6; quality = 0.3; }
        if (size > 10 && size <= 20) { scal= 0.65; quality = 0.2; }
        if (size > 20) { scal= 1.0; quality = 0.16; }

        // 压缩图片
        MultipartFile multipartFile = ImageCompressionUtil.compressMultipartFile(file,scal,quality);

        // 图片上传 minio
        String s = minioConfig.uploadImgObject(multipartFile);
        System.out.println("图片上传成功");
        MemeryInfoDTO m = new MemeryInfoDTO();
        m.setId(IdUtil.snowflakeId(32)); // id
        m.setImgTitle(formData.get("imgTitle").toString()); // imgTitle
        m.setIngDescription(formData.get("ingDescription").toString()); // ingDescription
        // imgTags -> 同学,同事,家人
        String[] imgTags = formData.get("imgTags").toString().split(",");
        String collect = Arrays.stream(imgTags).collect(Collectors.toSet()).stream().collect(Collectors.joining(","));
        m.setImgTags(collect); // imgTags
        m.setImgLetterUnchk(formData.get("imgLetterUnchk").toString()); // imgLetterUnchk
        m.setImgLetterChk(formData.get("imgLetterChk").toString()); // imgLetterChk
        m.setImgLike(Integer.valueOf(formData.get("imgLike").toString())); // imgLike
        m.setImgComment(Integer.valueOf(formData.get("imgComment").toString())); // imgComment
        m.setImgScan(Integer.valueOf(formData.get("imgScan").toString())); // imgScan
        m.setImgMinioRrl(s);// imgMinioRrl
        m.setImgFreezeOrnnt(0); // imgFreezeOrnnt
        // imgShowedRole 同学 同事 家人 女友 兄弟姐妹 大学同学...
        // 创建并初始化一个Map
        Map<String, String> map = new HashMap<String, String>() {{
            put("家乡", "1");put("我", "2");put("兄弟姐妹", "3");put("外甥", "4");
            put("六个核蛋", "5");put("日常", "6");put("GirlFriend", "7");put("大学", "8");
        }};
        List<String> values = Arrays.stream(imgTags)
            .map(map::get)
            .collect(Collectors.toList());
        String result = String.join(",", values);
        m.setImgShowedRole(result);
        Instant now = Instant.now();// 获取当前时间的Instant对象
        long timestamp = now.toEpochMilli();// 将Instant对象转换为毫秒级的timestamp
        // 如果你需要获取秒级的timestamp，可以使用toEpochSecond方法
        long timestampSeconds = now.getEpochSecond();
        Timestamp t = new Timestamp(timestampSeconds * 1000L);
        m.setImgRecordTm(t); // imgRecordTm
        m.setImgUpdateTm(t); // imgUpdateTm
        String avatarBase64 = netUtils.convertToBase64(s);
        m.setAvatarBase64(avatarBase64); // avatarBase64
        m.setPageSize(Integer.valueOf(formData.get("pageSize").toString())); // pageSize
        m.setCurrentPage(Integer.valueOf(formData.get("currentPage").toString()));// currentPage
        MemeryInfo memeryInfo = new MemeryInfo(
            m.getId(),m.getImgTitle(),m.getIngDescription(),m.getImgTags(),m.getImgLetterUnchk(),
            m.getImgLetterChk(),m.getImgLike(),m.getImgComment(),m.getImgScan(),m.getImgMinioRrl(),
            m.getImgFreezeOrnnt(),m.getImgShowedRole(),m.getImgRecordTm(),m.getImgUpdateTm(),0
        );
        int insert = memeryInfoMapper.insert(memeryInfo);
        ResponseDTO responseDTO = new ResponseDTO();
        if (insert > 0) {
            responseDTO.setCode(200);
            responseDTO.setData(m);
            responseDTO.setMsg("回忆存档成功！");
        } else {
            responseDTO.setCode(500);
            responseDTO.setMsg("回忆存档失败！");
        }
        return responseDTO;
    }

}
